package com.elasticsearch.dbuitl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Stack;

public class DB {
	private static DB DB_INSTANCE = null;
	private static int MAX = 40;
	private static Stack<Connection> CON_POOL = new Stack<Connection>();
	// 数据库配置
	private static String className = "com.mysql.jdbc.Driver";
	private static String url = "jdbc:mysql://localhost:3306/todo?useUnicode=true&characterEncoding=UTF-8";
	private static String username = "root";
	private static String password = "sa";
	// 同步对象
	private final static byte[] lock = new byte[0];

	private DB() throws ClassNotFoundException {
		Class.forName(className);

	}

	// 返回单一实例
	public static DB getInstance() throws ClassNotFoundException {
		if (DB_INSTANCE == null) {
			DB_INSTANCE = new DB();
		}
		return DB_INSTANCE;
	}

	// 获取连接
	public static Connection getConnection() throws SQLException {
		synchronized (lock) {
			if (CON_POOL.isEmpty()) {
				return DriverManager.getConnection(url, username, password);
			}
			return CON_POOL.pop();
		}
	}

	// 释放连接
	public static void release(Connection con) throws SQLException {
		synchronized (lock) {
			if (con == null || con.isClosed()) {
				return;
			} else if (CON_POOL.size() < MAX + 1) {
				CON_POOL.push(con);
			} else {
				con.close();
			}
		}
	}
}
